#!/usr/bin/python
# _*_ coding=utf-8 _*_
# Filename: tudou_tool.py

import sys
import os
import re
import urllib
import random

class TudouTool:
    '''Tudou tool, parse page url, compose video download url, download video
    '''

    class RequestParams:
        def __init__(self):
            self.pw = ""
            self.si = "10000"
            self.hd = "2"
            self.ui = "93677582"
            self.st = "1,2,3"
            self.vn = 02
            self.noCache = random.randint(1,65536)
            self.refurl = None
            self.it = None

    class ParseParams:
        def __init__(self):
            self.regx_iid = re.compile(r'[\s\S],iid\ =\ (.*)\r[\s\S]*')
            self.regx_volume_name = re.compile(r'[\s\S]*var g_chapter_name = "(.*)"[\s\S]*')
            self.regx_pages = re.compile(r"[\s\S]*var pages = '(\[.*\])'[\s\S]*")
            self.regx_next_volume = re.compile(r'[\s\S]*下一话.*href="(.*\.shtml)">(.*)</a>[\s\S]*')
            self.regx_image_suffix = re.compile(r'.*\.(.*)$')

    def __init__(self, page_url, save_dir):
        # manual params
        self._page_url = page_url
        self._save_dir = save_dir

        # url params
        self._request_params = RequestParams()
        self._request_params.refurl = page_url

        # parser params
        self._parse_params = ParseParams()

        # video info
        self._video_title = ""
        self._video_album_name = None
        self._video_album_num = None

        # downloader
        self._downloader = Downloader()

        # prepare temp dir
        self._tmp_path = "./var/tmp"
        if not os.path.exists(os.path.dirname(self._tmp_path)):
            os.makedirs(os.path.dirname(self._tmp_path))
            print '%s created' % str(os.path.dirname(self._tmp_path))
        

    def parsePage(self):
        # parse page
        opener = urllib.urlopen(self._page_url)
        buff = opener.read()
        print buff

        # parse manga title
        if not self.manga_title:
            m_manga_title = self.r_manga_title.match(buff)
            if not m_manga_title:
                print 'failed to find manga title'
                return 1
            self.manga_title = m_manga_title.group(1)
            print 'get manga title: %s' % self.manga_title
        else:
            print 'manga title exist: %s' % self.manga_title


    def composeVideoUrl(self):
        pass

    def downloadVideo(self):
        pass

    def start(self):
        parsePage()


class Downloader:
    '''Video downloader, download video from tudou
    '''
    def __init__(self):
        pass

    def download(self, url, save_dir):
        # compose save path
        file_name = "video.tmp"
        save_path = os.path.join(self._tmp_path, file_name)

        # download page
        if isinstance(self._page_url, unicode):
            page_url = str(self._page_url.encode('utf-8'))
        else:
            page_url = str(self._page_url.decode().encode('utf-8'))
            urllib.urlretrieve(page_url, save_path)
            print '%s --> %s' % (page_url, save_path)


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print 'usage: %s page_url save_dir' % (sys.argv[0])
        sys.exit(1)
    page_url = sys.argv[1]
    save_dir = sys.argv[2]
    tt = TudouTool(pages, save_dir)
    tt.start()

